import asyncio
from http import HTTPStatus
import platform

from dashscope import Generation
from dashscope.aigc.generation import AioGeneration
import dashscope
dashscope.api_key="sk-9d8f1914800e497f8717144e860f99bc"


async def async_dashscope_sample():
    response = await AioGeneration.call("qwen-turbo",
                                        prompt='今天天气好吗？')

    if response.status_code == HTTPStatus.OK:
        print('Result is: %s' % response.output)
    else:
        print('Failed request_id: %s, status_code: %s, code: %s, message:%s' %
              (response.request_id, response.status_code, response.code,
               response.message))


async def async_dashscope_stream_sample():
    responses = await AioGeneration.call(model="qwen-turbo",
                                         prompt='今天天气好吗？',
                                         stream=True)
    # responses是async迭代器，需要用async for循环来遍历
    async for response in responses:
        print(response)


async def main():
    response = await async_dashscope_sample()
    print(response)
    await async_dashscope_stream_sample()
if __name__ == '__main__':
    # 如果当前操作系统为Windows，则使用WindowsSelectorEventLoopPolicy作为事件循环策略
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.run(main(), debug=False)